package com.ztx.jpaTest;

import org.hibernate.jpa.QueryHints;
import org.junit.Test;

import javax.persistence.Query;
import java.util.List;

/**
 * JpaSecondCache--jpa-Demo
 *
 * @author: Jovi
 * @createTime: 2018-08-07 18:01
 **/
public class JpaSecondCache extends JpaTest {

    @Test
    public void testSecondLevelCache() {

        Customer c1 = entityManager.find(Customer.class, 1);

        transaction.commit();
        entityManager.close();

        entityManager = entityManagerFactory.createEntityManager();
        transaction = entityManager.getTransaction();
        transaction.begin();
        Customer c2 = entityManager.find(Customer.class, 1);
    }

    /**
     * 使用hibernate的查询缓存，前提是配置文件配置启用查询缓存
     * <property name="hibernate.cache.use_query_cache" value="true"/>
     */
    @Test
    public void testQueryCache() {

        String jpql = "FROM Customer c where c.age > ? ";
        Query query = entityManager.createQuery(jpql).setHint(QueryHints.HINT_CACHEABLE,true);

        //占位符索引从1开始
        query.setParameter(1, 10);
        List resultList = query.getResultList();
        System.out.println(resultList.size());

        query = entityManager.createQuery(jpql).setHint(QueryHints.HINT_CACHEABLE,true);

        //占位符索引从1开始
        query.setParameter(1, 10);
        resultList = query.getResultList();
        System.out.println(resultList.size());


    }
}
